$(function() {
	if (!window.WebSocket) {
		alert("WebSocket not supported by this browser");
	}

	$(window).resize(function() {
		init();
	});

	$('#setName').click(function() {
		settings();

	});

	$('#playerName').keypress(function(event) {
		if (event.which == '13') {
			settings();
		}
	});

	function settings() {
		var nameLength = $('#playerName').val().trim().length;
		if (nameLength > 0) {
			setPlayerName($('#playerName').val());
			$('#insertName').hide(1000, function() {
				$(this).remove();
				$('#fadeOutDiv').remove();
				$('#chooseBox').show();
			});
		}
		// get the chat history from local storage
		var $textarea = $('#messages');
		
		//init chati andmebaas
		initChatDB();
		
		getAllFromDB();
		
		//localstorage kasutades uncmment this
		//var text = getFromLocalStorage();
		//$textarea.val(text);
	}

	$('#sendMessage').click(function() {
		sendMessage();
	});

	$('#message').keypress(function(event) {
		if (event.which == '13') {
			sendMessage();
		}
	});

	$('#foldCanvas').click(function() {
		hideButtons();
		$.post("pokerservlet", {
			action : "fold"
		}, function(data) {
			handleAction(data);
		}, "json");
	});
	$('#foldCanvas').mouseover(function() {
		drawFoldButton(true);
	});
	$('#foldCanvas').mouseout(function() {
		drawFoldButton(false);
	});

	$('#raiseCanvas').click(function() {
		hideButtons();
		$.post("pokerservlet", {
			action : "raise"
		}, function(data) {
			handleAction(data);
		}, "json");
	});
	$('#raiseCanvas').mouseover(function() {
		drawRaiseButton(true);
	});
	$('#raiseCanvas').mouseout(function() {
		drawRaiseButton(false);
	});

	$('#callCanvas').click(function() {
		hideButtons();
		$.post("pokerservlet", {
			action : "call"
		}, function(data) {
			handleAction(data);
		}, "json");
	});
	$('#callCanvas').mouseover(function() {
		drawCallButton(true);
	});
	$('#callCanvas').mouseout(function() {
		drawCallButton(false);
	});

	/* Alusta nupp */
	$('#beginCanvas').click(function() {
		$('#beginCanvas').hide();
		$.post("pokerservlet", {
			action : "handStart",
			index : playerIndex
		}, function(data) {
			handStart(data);
		}, "json");
	});
	$('#beginCanvas').mouseover(function() {
		drawBeginButton(true);
	});
	$('#beginCanvas').mouseout(function() {
		drawBeginButton(false);
	});
	/* Alusta nupp */

	/* Koha valimise event handlerid */
	for ( var i = 1; i <= 9; i++) {
		var id = '#area' + i;
		$(id).data("index", i);
		$(id).mouseover(function() {
			drawPlayerBox($(this).data('index'), true);
		});
		$(id).mouseout(function() {
			drawPlayerBox($(this).data('index'), false);
		});
		$(id).click(function() {
			handlePlayerBoxClick($(this).data('index'));
		});
	}
	/* Koha valimise event handlerid */

	$('#chooseBox').hide();
	$('canvas[id^="player"]').hide();
	hideButtons();
	$('#bankCanvas').hide();
	init();
	$('#playerName').focus();
	createNameBox();
});

/* Globaalsed muutujad */
var tableWidth;
var tableHeight;
var tableCenterX;
var tableCenterY;

var windowX;
var windowY;

var playerName = null;
var playerIndex = null;
var initialLoad = true;
var playerBox = new Array();
var buttons = new Array();
var activebuttons;
var activePlayer = 0;
/* Globaalsed muutujad */

function getTableWidth() {
	return tableWidth;
}

function getTableHeight() {
	return tableHeight;
}

function getTableCenterX() {
	return tableCenterX;
}

function getTableCenterY() {
	return tableCenterY;
}

function setActivePlayer(player) {
	activePlayer = player;
}

function getActivePlayer() {
	activePlayer;
}

function createNameBox() {
	var boxWidth = getTableWidth() / 3;
	var boxHeight = getTableHeight() / 3;
	var left = getTableCenterX() - boxWidth / 2;
	var top = getTableCenterY() - boxHeight / 2;
	$('#insertName').css({
		'width' : boxWidth,
		'height' : boxHeight,
		'left' : left,
		'top' : top
	});
}

function setFadeOut(active) {
	if (active) {
		initialLoad = false;
		var fadeCanvas = document.getElementById("fadeOut");
		var context = fadeCanvas.getContext("2d");
		context.fillStyle = "rgb(0, 0, 0)";
		context.fillRect(0, 0, context.canvas.width, context.canvas.height);
	}
}

function setPlayerIndex(index) {
	this.playerIndex = index;
	$('#player' + index).attr('name', getPlayerName());
}

function getPlayerIndex() {
	return this.playerIndex;
}

function setPlayerName(setName) {
	this.playerName = setName;
}

function getPlayerName() {
	return this.playerName;
}

function getRatio() {
	var fRatio = screen.width / screen.height;
	return fRatio;
}

function setCoordinates() {
	windowX = window.innerWidth / 2;
	windowY = window.innerHeight / 2;
}

function getDiagonal() {
	return Math.sqrt(square(window.innerWidth) + square(window.innerHeight));
}

function init() {
	setCoordinates();
	drawTable();
	drawPlayerBoxes();
	drawChooseBox();
	drawBeginButton(false);
	drawFoldButton(false);
	drawCallButton(false);
	drawRaiseButton(false);
	drawBank(getPotValue());
	setButtonDivLocation();
	setFadeOut(initialLoad);
	if (isCardsDealt()) {
		if (isShowDown()) {
			reDrawShowDown();
		} else {
			reDrawCards();
		}
		if (isFlopDealt()) {
			reDrawFlop();
			if (isTurnDealt()) {
				reDrawTurn();
				if (isRiverDealt()) {
					reDrawRiver();
				}
			}
		}
	}
	if (isDealerButtonSet()) {
		modifyDealerLocation();
	}
}

function drawChooseBox() {
	var canvasId = "chooseBox";
	var canvas = document.getElementById(canvasId);
	var context = canvas.getContext("2d");
	if (context) {
		var sizes = getPlayerBoxValues();
		var width = sizes["width"] * (3 / 2);
		var height = sizes["height"] / 2;
		context.canvas.width = width;
		context.canvas.height = height;
		context.fillStyle = "#FFFFFF";
		var fontSize = sizes["width"] * 0.2;
		context.font = "bold " + fontSize + "px Arial";
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		var text = 'Choose Seat';
		context.fillText(text, width / 2, height / 2);
		setLocation(canvasId, getTableCenterX() - (width / 2),
				getTableCenterY() - (height / 2));
	}
}

function setButtonDivLocation() {
	var buttonSize = getButtonsValues();
	var divWidth = (activebuttons + 0.1) * buttonSize["width"];
	var divHeight = buttonSize["height"];
	var x = $(document).width() / 2;
	var y = getTableCenterY() + (getTableHeight() / 2)
			+ getPlayerBoxValues()["height"] * (3 / 2);
	$('#buttonDiv').css({
		width : divWidth,
		height : divHeight
	});
	setLocation('buttonDiv', x, y);
}

function drawTable() {
	var canvas = document.getElementById("tableCanvas");
	var context = canvas.getContext("2d");
	if (context) {
		var maxWidth = 600;
		var minWidth = maxWidth * (2 / 3);
		var diag = getDiagonal();
		tableWidth = diag / 2;
		if (tableWidth > maxWidth) {
			tableWidth = maxWidth;
		}
		if (tableWidth < minWidth) {
			tableWidth = minWidth;
		}
		tableHeight = tableWidth * 0.45;

		var lineWidth = tableWidth * (1 / 30);
		if (lineWidth > 20) {
			lineWidth = 20;
		}
		var shadowBlur = tableWidth * 0.05;
		context.canvas.width = tableWidth + lineWidth + shadowBlur;
		context.canvas.height = tableHeight + lineWidth + shadowBlur;

		var controlY = (tableWidth - tableHeight) / 2;
		var centerX = context.canvas.width / 2;
		var centerY = context.canvas.height / 2;

		context.beginPath();

		// left arc
		context.arc(centerX - controlY, centerY, tableHeight / 2, -Math.PI / 2,
				Math.PI / 2, true);

		// right arc
		context.arc(centerX + controlY, centerY, tableHeight / 2, Math.PI / 2,
				-Math.PI / 2, true);

		// gradient
		var startR = tableHeight / 5;
		var endR = tableHeight * 1.5;

		var grad = context.createRadialGradient(centerX, centerY, startR,
				centerX, centerY, endR);
		grad.addColorStop(0, "rgb(193, 9, 9)");
		grad.addColorStop(1, "black");
		context.fillStyle = grad;
		context.fill();
		context.lineWidth = lineWidth;
		context.strokeStyle = "#70430C";

		context.shadowOffsetX = 0;
		context.shadowOffsetY = 0;
		context.shadowBlur = shadowBlur;
		context.shadowColor = "black";

		context.closePath();
		context.stroke();

		context.closePath();
		var x = windowX - context.canvas.width / 2;
		var y = windowY - context.canvas.height / 1.5;
		tableCenterX = x + context.canvas.width / 2;
		tableCenterY = y + context.canvas.height / 2;
		setLocation('tableCanvas', x, y);
	}
}

function setLocation(id, x, y) {
	var id = '#' + id;
	$(id).css({
		'position' : 'absolute',
		'left' : x,
		'top' : y
	});
}

function drawBank(amount) {
	var canvasId = "bankCanvas";
	var canvas = document.getElementById(canvasId);
	clearCanvas(canvas);
	var context = canvas.getContext("2d");
	var lineWidth = 3;
	var width = (tableWidth / 5);
	var height = (tableHeight / 5);
	var canvasWidth = width + lineWidth;
	var canvasHeight = height + lineWidth;
	context.canvas.width = canvasWidth;
	context.canvas.height = canvasHeight;
	context.strokeStyle = "#6D645E";
	context.fillStyle = "#000000";
	context.lineWidth = lineWidth;
	roundRect(context, lineWidth / 2, lineWidth / 2, width, height, 8);
	context.fillStyle = "#FFFFFF";
	var fontSize = canvasWidth * 0.12;
	context.font = "bold " + fontSize + "px Arial";
	context.textAlign = 'center';
	context.textBaseline = 'middle';
	var text = "Total Pot";
	context.fillText(text, canvasWidth / 2, canvasHeight / 3);
	context.fillText(amount, canvasWidth / 2, canvasHeight * (2 / 3));
	var left = getTableCenterX() - canvasWidth / 2;
	var top = getTableCenterY() - getTableHeight() / 2 - height / 2;
	setLocation(canvasId, left, top);
}

function drawBeginButton(active) {
	var beginCanvas = document.getElementById("beginCanvas");
	clearCanvas(beginCanvas);
	var context = beginCanvas.getContext("2d");
	if (context) {
		var buttonWidth = tableWidth / 5;
		var buttonHeight = buttonWidth / 2;
		var lineWidth = 3;
		var canvasWidth = buttonWidth + lineWidth;
		var canvasHeight = buttonHeight + lineWidth;
		context.canvas.width = canvasWidth;
		context.canvas.height = canvasHeight;
		setButtonsValues(canvasWidth, canvasHeight);
		var grd = context.createLinearGradient(canvasWidth / 2, 0,
				canvasWidth / 2, canvasHeight / 2);
		grd.addColorStop(0, "#603311");
		grd.addColorStop(1, "#000000");
		var backColor = "#FFFFFF";
		var textColor = "#CAC092";
		if (active) {
			context.strokeStyle = backColor;
		} else {
			context.strokeStyle = "#855E42";
		}
		context.fillStyle = grd;
		context.lineWidth = lineWidth;
		roundRect(context, lineWidth / 2, lineWidth / 2, buttonWidth,
				buttonHeight, 8);
		var fontSize = buttonWidth * 0.15;
		if (active) {
			context.fillStyle = backColor;
		} else {
			context.fillStyle = textColor;
		}
		context.font = "bold " + fontSize + "px Arial";
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		var name = 'BEGIN';
		context.fillText(name, canvasWidth / 2, canvasHeight / 2);
	}
}

function drawCallButton(active) {
	var callCanvas = document.getElementById("callCanvas");
	clearCanvas(callCanvas);
	var context = callCanvas.getContext("2d");
	if (context) {
		var buttonWidth = tableWidth / 5;
		var buttonHeight = buttonWidth / 2;
		var lineWidth = 3;
		var canvasWidth = buttonWidth + lineWidth;
		var canvasHeight = buttonHeight + lineWidth;
		context.canvas.width = canvasWidth;
		context.canvas.height = canvasHeight;
		var grd = context.createLinearGradient(canvasWidth / 2, 0,
				canvasWidth / 2, canvasHeight / 2);
		grd.addColorStop(0, "#4789BB");
		grd.addColorStop(1, "#000000");
		var backColor = "#FFFFFF";
		var textColor = "#CAC092";
		if (active) {
			context.strokeStyle = backColor;
		} else {
			context.strokeStyle = "#855E42";
		}
		context.fillStyle = grd;
		context.lineWidth = lineWidth;
		roundRect(context, lineWidth / 2, lineWidth / 2, buttonWidth,
				buttonHeight, 8);
		var fontSize = buttonWidth * 0.15;
		if (active) {
			context.fillStyle = backColor;
		} else {
			context.fillStyle = textColor;
		}
		context.font = "bold " + fontSize + "px Arial";
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		var name = 'CALL';
		if (getPreviousBet() == 0) {
			name = 'CHECK';
		}
		context.fillText(name, canvasWidth / 2, canvasHeight / 2);
	}
}

function drawRaiseButton(active) {
	var raiseCanvas = document.getElementById("raiseCanvas");
	clearCanvas(raiseCanvas);
	var context = raiseCanvas.getContext("2d");
	if (context) {
		var buttonWidth = tableWidth / 5;
		var buttonHeight = buttonWidth / 2;
		var lineWidth = 3;
		var canvasWidth = buttonWidth + lineWidth;
		var canvasHeight = buttonHeight + lineWidth;
		context.canvas.width = canvasWidth;
		context.canvas.height = canvasHeight;
		var grd = context.createLinearGradient(canvasWidth / 2, 0,
				canvasWidth / 2, canvasHeight / 2);
		grd.addColorStop(0, "#23BE0B");
		grd.addColorStop(1, "#000000");
		var backColor = "#FFFFFF";
		var textColor = "#CAC092";
		if (active) {
			context.strokeStyle = backColor;
		} else {
			context.strokeStyle = "#855E42";
		}
		context.fillStyle = grd;
		context.lineWidth = lineWidth;
		roundRect(context, lineWidth / 2, lineWidth / 2, buttonWidth,
				buttonHeight, 8);
		var fontSize = buttonWidth * 0.15;
		if (active) {
			context.fillStyle = backColor;
		} else {
			context.fillStyle = textColor;
		}
		context.font = "bold " + fontSize + "px Arial";
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		var name = 'RAISE';
		context.fillText(name, canvasWidth / 2, canvasHeight / 2);
	}
}

function drawFoldButton(active) {
	var foldCanvas = document.getElementById("foldCanvas");
	clearCanvas(foldCanvas);
	var context = foldCanvas.getContext("2d");
	if (context) {
		var buttonWidth = tableWidth / 5;
		var buttonHeight = buttonWidth / 2;
		var lineWidth = 3;
		var canvasWidth = buttonWidth + lineWidth;
		var canvasHeight = buttonHeight + lineWidth;
		context.canvas.width = canvasWidth;
		context.canvas.height = canvasHeight;
		var grd = context.createLinearGradient(canvasWidth / 2, 0,
				canvasWidth / 2, canvasHeight / 2);
		grd.addColorStop(0, "#BD1009");
		grd.addColorStop(1, "#000000");
		var backColor = "#FFFFFF";
		var textColor = "#CAC092";
		if (active) {
			context.strokeStyle = backColor;
		} else {
			context.strokeStyle = "#855E42";
		}
		context.fillStyle = grd;
		context.lineWidth = lineWidth;
		roundRect(context, lineWidth / 2, lineWidth / 2, buttonWidth,
				buttonHeight, 8);
		var fontSize = buttonWidth * 0.15;
		if (active) {
			context.fillStyle = backColor;
		} else {
			context.fillStyle = textColor;
		}
		context.font = "bold " + fontSize + "px Arial";
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		var name = 'FOLD';
		context.fillText(name, canvasWidth / 2, canvasHeight / 2);
	}
}

function drawPlayerBoxes() {
	var players = 9;
	for ( var int = 1; int <= players; int++) {
		drawPlayerBox(int, false);
		var active = (int == getActivePlayer()) ? true : false;
		drawPlayer(int, getPlayerNames(int), getPlayerStacks(int), active);
	}
}

function drawPlayer(id, name, stack, active) {
	var playerId = "player" + id;
	var playerCanvas = document.getElementById(playerId);
	clearCanvas(playerCanvas);
	var context = playerCanvas.getContext("2d");
	if (context) {
		var sizes = getPlayerBoxValues();
		context.canvas.width = sizes["width"];
		context.canvas.height = sizes["height"];
		if (active) {
			context.fillStyle = "#FFFFFF";

		} else {
			context.fillStyle = "#6D645E";

		}
		var fontSize = sizes["width"] * 0.10;
		context.font = "bold " + fontSize + "px Arial";
		context.textAlign = 'center';
		context.textBaseline = 'top';
		if (name) {
			context.fillText(name, sizes["width"] / 2, sizes["height"]
					* (2 / 3));
		}
		if (stack) {
			context.fillText(stack, sizes["width"] / 2, sizes["height"]
					* (2 / 3) + fontSize);
		}
		var location = getBoxLocation(id, sizes["width"], sizes["height"]);
		setLocation(playerId, location[0], location[1]);
	}
}

function drawPlayerBox(index, active) {
	var canvasId = "area" + index;
	var canvas = document.getElementById(canvasId);
	var context = canvas.getContext("2d");
	var lineWidth = 3;
	var width = (tableWidth / 5);
	var height = (tableHeight / 3);
	var canvasWidth = width + lineWidth;
	var canvasHeight = height + lineWidth;
	context.canvas.width = canvasWidth;
	context.canvas.height = canvasHeight;
	setPlayerBoxValues(canvasWidth, canvasHeight);
	if (active) {
		context.strokeStyle = "#FFFFFF";
	} else {
		context.strokeStyle = "#6D645E";
	}
	context.fillStyle = "#000000";
	context.lineWidth = lineWidth;
	roundRect(context, lineWidth / 2, lineWidth / 2, width, height, 8);
	var location = getBoxLocation(index, canvasWidth, canvasHeight);
	setLocation(canvasId, location[0], location[1]);
}

function setPlayerBoxValues(canvasWidth, canvasHeight) {
	playerBox["width"] = canvasWidth;
	playerBox["height"] = canvasHeight;
}

function getPlayerBoxValues() {
	return playerBox;
}

function setButtonsValues(buttonWidth, buttonHeight) {
	buttons["width"] = buttonWidth;
	buttons["height"] = buttonHeight;
}

function getButtonsValues() {
	return buttons;
}

function sendMessage() {
	var message = $('#message').val();
	if (message.trim().length > 0) {
		addMessage(message, getPlayerName());
		room.chat(message);
		// $.post("pokerservlet", {
		// action : "chat"
		// }, function(data) {
		// if (data != null) {
		// var content = data.message;
		// addMessage(content, data.name);
		// }
		// }, "json");
		$('#message').val('');
	}
}

function square(x) {
	return x * x;
}

function clearCanvas(canvas) {
	if (canvas) {
		var context = canvas.getContext("2d");
		context.clearRect(0, 0, canvas.width, canvas.height);
		var w = canvas.width;
		canvas.width = 1;
		canvas.width = w;
	}
}

function showButtons(begin, fold, call, raise) {
	var buttons = 0;
	if (begin) {
		$('#beginCanvas').show();
		buttons++;
	}
	if (fold) {
		$('#foldCanvas').show();
		buttons++;
	}
	if (call) {
		drawCallButton(false);
		$('#callCanvas').show();
		buttons++;
	}
	if (raise) {
		$('#raiseCanvas').show();
		buttons++;
	}
	activebuttons = buttons;
	setButtonDivLocation();
	$('#buttonDiv').show();
}

function hideButtons() {
	$('#beginCanvas').hide();
	$('#raiseCanvas').hide();
	$('#callCanvas').hide();
	$('#foldCanvas').hide();
	$('#buttonDiv').hide();
}

function handlePlayerBoxClick(index) {
	setPlayerIndex(index);
	$.post("pokerservlet", {
		action : "gameStart",
		index : getPlayerIndex(),
		name : getPlayerName()
	}, function(data) {
		drawPlayerBox(getPlayerIndex(), false);
		$('#chooseBox').hide();
		var players = data.players;
		for ( var i = 0; i < players.length; i++) {
			var playerBoxId = "#area" + (i + 1);
			$(playerBoxId).unbind();
			drawPlayer(players[i].index, players[i].name, players[i].stack,
					false);
			addPlayer(players[i].index, players[i].name, players[i].stack);
		}
		$('canvas[id^="player"]').show();
		$('#bankCanvas').show();
		showButtons(true, false, false, false);
		room.join();
	}, "json");
}

function getBoxLocation(index, canvasWidth, canvasHeight) {
	switch (index) {
	case 1:
		return [ tableCenterX - (tableWidth / 2 + canvasWidth * (4 / 5)),
				tableCenterY - (tableHeight / 5 + canvasHeight) ];
		break;
	case 2:
		return [ tableCenterX - (tableWidth / 3),
				tableCenterY - (tableHeight / 2 + canvasHeight) ];
		break;
	case 3:
		return [ tableCenterX + (tableWidth / 3 - canvasWidth),
				tableCenterY - (tableHeight / 2 + canvasHeight) ];
		break;
	case 4:
		return [ tableCenterX + (tableWidth / 2 - canvasWidth * (1 / 5)),
				tableCenterY - (tableHeight / 5 + canvasHeight) ];
		break;
	case 5:
		return [ tableCenterX + (tableWidth / 2 - canvasWidth * (1 / 5)),
				tableCenterY + (tableHeight / 5) ];
		break;
	case 6:
		return [ tableCenterX + (tableWidth / 3 - canvasWidth * (4 / 5)),
				tableCenterY + (tableHeight / 4 + canvasHeight * (2 / 3)) ];
		break;
	case 7:
		return [ tableCenterX - (canvasWidth / 2),
				tableCenterY + (tableHeight / 4 + canvasHeight * (2 / 3)) ];
		break;
	case 8:
		return [ tableCenterX - (tableWidth / 3 + canvasWidth * (1 / 5)),
				tableCenterY + (tableHeight / 4 + canvasHeight * (2 / 3)) ];
		break;
	case 9:
		return [ tableCenterX - (tableWidth / 2 + canvasWidth * (4 / 5)),
				tableCenterY + (tableHeight / 5) ];
		break;
	}
}

/**
 * Draws a rounded corner rectangle, used for drawing player area boxes
 * 
 * @param ctx
 * @param x
 * @param y
 * @param width
 * @param height
 * @param radius
 * @return
 */
function roundRect(ctx, x, y, width, height, radius) {
	ctx.beginPath();
	ctx.moveTo(x + radius, y);
	ctx.lineTo(x + width - radius, y);
	ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
	ctx.lineTo(x + width, y + height - radius);
	ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
	ctx.lineTo(x + radius, y + height);
	ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
	ctx.lineTo(x, y + radius);
	ctx.quadraticCurveTo(x, y, x + radius, y);
	ctx.closePath();
	ctx.stroke();
	ctx.fill();
}